import $store from './../../../store';
import $toast from './../../../components/toast';
import $confirm from './../../../components/confirm';
// 接口服务
import buyTicketService from './../../../api/buyTicketService.js';


export class BuyTicket {
  // 更新购物车信息(加减票操作)
  // operator:运算符 => reduceTicket:减少票  addTicket:增加票
  // ticket:票 =>  单笔增减或者减少票的信息数据
  async upDataCarTicket(operator, ticket) {

    if ($store.state.buyTicket.soldOut) {
      $toast('已售罄');
      return;
    }
    if (!$store.state.buyTicket.noSale) {
      $toast('暂未开售');
      return;
    }

    //增加票
    if (operator === 'addTicket') {
      if (!$store.state.buyTicket.limitNum) {
        $toast('未获取到限购数量');
        return;
      }

      //单笔订单限购数量
      if (ticket.limitNum && buyTicket.regTicket(ticket.ticketId, ticket.limitNum)) {
        $toast('该门票已达订单限购数量');
        return;
      }



      // 单票不可以超过规定张
      if (buyTicket.regTicket(ticket.ticketId, $store.state.buyTicket.limitNum)) {
        // $store.state.buyTicket.alert = true;
        await $confirm(`单笔订单超过${$store.state.buyTicket.limitNum}张建议通过邮件团购${$store.state.buyTicket.connectEmail}`, {
          title: "已达限购数",
          okLabel: "知道了",
          showCancel: false
        });
        return;
      }
      // 每笔订单最多可以选购规定张票
      if ($store.state.buyTicket.carTicketSumList.length > $store.state.buyTicket.limitNum - 1) {
        // $toast(`每笔订单最多可以选购${$store.state.buyTicket.limitNum}张票`);
        // $store.state.buyTicket.alert = true;
        await $confirm(`单笔订单超过${$store.state.buyTicket.limitNum}张建议通过邮件团购${$store.state.buyTicket.connectEmail}`, {
          title: "已达限购数",
          okLabel: "知道了",
          showCancel: false
        });
        return;
      }

      // 判断当前票购买是否可以超过库存量
      let getTicketNum = await buyTicket.getTicketNum(ticket.ticketId); //得到当前票在购物车中的数量
      if (getTicketNum >= (Number(ticket.inum) || 0)) {
        $toast('库存不足');
        return;
      }


      $store.state.buyTicket.carTicketSumList.push(ticket); //增加票
      // 对接接口 保存数据  //没有购物车暂存的。首页先注释
      // let res = await buyTicketService.upDataCarTicketService(ticket);
      let arrangementDataCarTicket = await buyTicket.arrangementDataCarTicket('addTicket', ticket); // 整理购物车的数据(增加减少时候拿所有的票carTicketSumLis整理成购物车carTicketList的数据格式)
      buyTicket.calculationPrice(); //计算价格-增加
    }

    if (operator === 'reduceTicket') {
      // 单种票减少到0以后不可以减少,及购物车中是否有当前票
      if (!buyTicket.carHaveTicket(ticket.ticketId)) {
        $toast('您需要选择购票');
        return;
      }
      let carTicketSumList = $store.state.buyTicket.carTicketSumList;
      for (let i = 0; i < carTicketSumList.length; i++) {
        if (ticket.ticketId === carTicketSumList[i].ticketId) {
          $store.state.buyTicket.carTicketSumList.splice(i, 1); //减少票
          let arrangementDataCarTicket = await buyTicket.arrangementDataCarTicket('reduceTicket', ticket); // 整理购物车的数据(增加减少时候拿所有的票carTicketSumLis整理成购物车carTicketList的数据格式)
          buyTicket.calculationPrice(); //计算价格-减少
          break;
        }
      }
    }

  }
  // 得到当前票在购物车中的数量
  getTicketNum(ticketId) {
    return new Promise((resolve) => {
      let num = 0;
      let carTicketList = $store.state.buyTicket.carTicketList;
      for (let i = 0; i < carTicketList.length; i++) {
        if (
          carTicketList[i].body_ticket &&
          carTicketList[i].body_ticket.length !== 0 &&
          ticketId === carTicketList[i].body_ticket[0].ticketId
        ) {
          num = carTicketList[i].body_ticket.length;
          break;
        }
      }
      resolve(num);
    });
  };
  // 计算价格
  calculationPrice() {
    let carTicketSumList = $store.state.buyTicket.carTicketSumList; //所有的票没有整理数据的
    let totalPrice = 0; // 总的价格 Number($store.state.buyTicket.totalPrice) ||
    let actualPrice = 0; // 实际的价格  Number($store.state.buyTicket.actualPrice) ||
    for (let i = 0; i < carTicketSumList.length; i++) {
      totalPrice += Number(carTicketSumList[i].sprice) || 0;
      actualPrice += Number(carTicketSumList[i].eprice) || 0; //实际价格-0;//注意这里是单张票的打折，所以不要改
    }
    $store.state.buyTicket.totalPrice = totalPrice.toFixed(2);
    $store.state.buyTicket.actualPrice = actualPrice.toFixed(2);
    $store.state.buyTicket.foldUpBeforeActualPrice = $store.state.buyTicket.actualPrice; //进行折上折之前的实际的价格

    // 计算折上折
    let foldUp = $store.state.buyTicket.foldUp || []; //打折的规则
    if (sessionStorage.getItem("foldUp") && foldUp.length == 0) {
      foldUp = JSON.parse(sessionStorage.getItem("foldUp"));
    }
    console.log('打折规则', foldUp);

    $store.state.buyTicket.foldUpTicket = []; //得到参与打折的门票（清空处理）
    $store.state.buyTicket.sureFoldUp = 10; //确定打几折
    if (foldUp.length != 0 && foldUp[0].ticketTypeIds) { //要有打折规则&&可以获取到打折门票的数组ID（ticketId）
      for (let i = 0; i < carTicketSumList.length; i++) { //拿购物车中的数量进行比较
        if (JSON.parse(foldUp[0].ticketTypeIds).indexOf(carTicketSumList[i].ticketId) >= 0) { //判断当前门票是否属于参与打折的门票( // 只打折选中的门票)
          $store.state.buyTicket.foldUpTicket.push(carTicketSumList[i]);
        }
      }
    }
    console.log('打折的门票', $store.state.buyTicket.foldUpTicket);
    // 得到整体要打几折
    let foldUpTicketLength = $store.state.buyTicket.foldUpTicket.length;
    for (let i = 0; i < foldUp.length; i++) {
      if (foldUpTicketLength >= foldUp[i].discountNum) {
        $store.state.buyTicket.sureFoldUp = Number(foldUp[i].discount) || 10;
      }
    }
    console.log("打几折", $store.state.buyTicket.sureFoldUp);

    //计算折上折
    let actualPriceAginSum = 0; //计算再一次的实际的价格
    for (let i = 0; i < $store.state.buyTicket.foldUpTicket.length; i++) {
      actualPriceAginSum = (actualPriceAginSum + Number($store.state.buyTicket.foldUpTicket[i].eprice) || 0); //实际价格-0;//注意这里是单张票的打折
    }
    actualPriceAginSum = actualPriceAginSum.toFixed(2);
    console.log('打折之前实际价格', actualPriceAginSum);
    let actualPriceAgin = (actualPriceAginSum * ($store.state.buyTicket.sureFoldUp / 10)).toFixed(2);
    console.log("在一次减少", actualPriceAgin);
    $store.state.buyTicket.actualPrice = ($store.state.buyTicket.actualPrice - (actualPriceAginSum - actualPriceAgin).toFixed(2)).toFixed(2); //实际价格减去在一次优惠的，得到再一次减少多少，在用原来的实际价格减去再一次减少的；
  }
  // 整理购物车的数据(增加减少时候拿所有的票carTicketSumLis整理成购物车carTicketList的数据格式)
  arrangementDataCarTicket(operator, ticket) {
    return new Promise((resolve) => {
      //增加票
      if (operator === 'addTicket') {
        // 判断购物车中是否有当前票
        if (buyTicket.carHaveTicket(ticket.ticketId)) {
          // 如果有当前票则在当前中加
          let carTicketList = $store.state.buyTicket.carTicketList;
          for (let i = 0; i < carTicketList.length; i++) {
            if (carTicketList[i].body_ticket && carTicketList[i].body_ticket.length !== 0 && ticket.ticketId === carTicketList[i].body_ticket[0].ticketId) {
              carTicketList[i].body_ticket.push(ticket);
              break;
            }
          }
          $store.state.buyTicket.carTicketList = carTicketList;
        } else {
          // 如果没有当前票
          let obj = {
            head: {},
            body_ticket: []
          };
          obj.body_ticket.push(ticket);
          $store.state.buyTicket.carTicketList.push(obj);
        }
      }

      // 减少票
      if (operator === 'reduceTicket') {
        let carTicketList = $store.state.buyTicket.carTicketList;
        for (let i = 0; i < carTicketList.length; i++) {
          if (carTicketList[i].body_ticket && carTicketList[i].body_ticket.length !== 0 && ticket.ticketId === carTicketList[i].body_ticket[0].ticketId) {
            carTicketList[i].body_ticket.splice(0, 1);
            if (carTicketList[i].body_ticket.length === 0) {
              carTicketList.splice(i, 1);
            }
            break;
          }
        }
        $store.state.buyTicket.carTicketList = carTicketList;
      }

      //添加用票人信息数据
      let carTicketList = $store.state.buyTicket.carTicketList;
      for (let i = 0; i < carTicketList.length; i++) {
        let useTicketPople = []; //新的数组存放用票人信息
        let useTicketPopleItems = carTicketList[i].useTicketPople; //存放原有的值
        carTicketList[i].useTicketPople = []; //原有的值进行清空重新赋值
        for (let j = 0; j < carTicketList[i].body_ticket.length; j++) {
          if (useTicketPopleItems) {
            // 如果原来有值
            if (useTicketPopleItems[j]) {
              // 判断原来当前位是否有值，如果有值则取原来的
              useTicketPople.push(useTicketPopleItems[j]);
            } else {
              // 如果没有则生成
              let obj = {
                useTicketPopleId: Number(new Date()) + Math.random(), //根据时间戳生成唯一id
              };
              useTicketPople.push(obj);
            }
          } else {
            // 如果原有没有值则定义添加
            let obj = {
              useTicketPopleId: Number(new Date()) + Math.random(), //根据时间戳生成唯一id
            };
            useTicketPople.push(obj);
          }
        }
        carTicketList[i].useTicketPople = useTicketPople;
      }
      // console.log($store.state.buyTicket.carTicketList);
      resolve('ok');
    });
  }
  // 单种票减少到0以后不可以减少,及购物车中是否有当前票
  carHaveTicket(ticketId) {
    let value = false; //默认购物车中没有有当前票
    let carTicketList = $store.state.buyTicket.carTicketList;
    for (let i = 0; i < carTicketList.length; i++) {
      if (carTicketList[i].body_ticket && carTicketList[i].body_ticket.length !== 0 && ticketId === carTicketList[i].body_ticket[0].ticketId) {
        value = true;
        break;
      }
    }
    return value;
  }
  // 判断单种票购买的数量是否超过规定值
  regTicket(ticketId, num) {
    let carTicketList = $store.state.buyTicket.carTicketList;
    let value = false; //默认没有超过
    for (let i = 0; i < carTicketList.length; i++) {
      if (carTicketList[i].body_ticket && carTicketList[i].body_ticket.length !== 0 && ticketId === carTicketList[i].body_ticket[0].ticketId && carTicketList[i].body_ticket.length >= num) {
        value = true;
        break;
      }
    }
    return value;
  }
  // 清空购物车
  clearGoods() {
    $confirm('清空购物车？', {
      title: '',
      okLabel: '清空',
      showCancel: true
    }).then(result => {
      if (result) {
        $store.state.buyTicket.carTicketList = [];
        $store.state.buyTicket.carTicketSumList = [];
        $store.state.buyTicket.totalPrice = 0;
        $store.state.buyTicket.actualPrice = 0;
        $toast('清空成功');
      }
    });
  }
}

let buyTicket = new BuyTicket();
export default buyTicket;
